<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/20 14:41
 * Modified Time: 2019/7/20 14:41
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class WxGetMemberCardInfo extends BaseCriterias
{
    private $member_card_id;

    public function __construct($member_card_id)
    {
        $this->member_card_id = $member_card_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {

        $member_card_id = $this->member_card_id;



        $select = [
            'hx_member_card.id',
            'hx_member_card.name',
            'hx_member_card.type_id',
            'hx_card_type.category',
            'IF(hx_card_type.category=1,"次数卡","充值卡") as card_category',
            'hx_member_card.balance',
            'DATE_FORMAT(hx_member_card.created_at,"%Y/%m/%d") as created_time'
        ];

        $select = implode($select,',');

        $model = $model->selectRaw($select)
            ->leftJoin('card_type','member_card.type_id','card_type.id')
            ->with(['memberCardFlow'=>function($query){
                $select = [
                    'card_id',
                    'sum(real_amount) as count'
                ];

                $select = implode($select,',');
                $query->selectRaw($select)
                    ->where('type','<>',3);
            }])
            ->with(['cardType'=>function($query){
                $select = [
                    'id',
                    'name'
                ];

                $select = implode($select,',');
                $query->selectRaw($select);
            }])
            ->where('member_card.id',$member_card_id)

        ;

        return $model;
    }
}